'''
 * Created by PyCharm.
 * User: longbob
 * Date: 2018/9/18 0018
 * Time: 14:50
'''
from time import time, sleep

from websocket import create_connection
import threading
import json.encoder
import os


class WebSocket:
    _protocol = "ws://"
    _wsClient = None
    _rectThead = None

    """
        建立连接
    """

    def connect(self, url, token):
        self._wsClient = create_connection(self._protocol + url, header=[
            'Authorization:' + token
        ])
        if self._wsClient.connected:
            # 启动心跳线程
            self._rectThead = threading.Thread(target=self.rect)
            self._rectThead.start()
            getResT = threading.Thread(target=self.getRequestRes)
            getResT.start()
            print('connect succeed')
            while True:
                data = str(input('data:'))
                if data == 'exit':
                    self._exit()
                    return
                self.send(data)

    """
        发送数据包
    """

    def send(self, data):
        lenNum = self._wsClient.send(data)
        if lenNum:
            print('发送成功[成功发送%d字节]' % lenNum)
        else:
            print('发送失败')

    """
        关闭连接
    """

    def close(self):
        print('关闭连接')
        self._wsClient.close()

    """
        获取响应数据报文
    """

    def getRequestRes(self):
        while True:
            res = self._wsClient.recv()
            if res:
                print(res)
            sleep(0.01)

    def rect(self):
        while True:
            sleep(30)
            self.send(
                json.dumps({
                    "chancel": "Main",
                    "eventName": "rect",
                    "timestamp": int(time()),
                    "data": []
                })
            )

    def _exit(self):
        self.close()
        os._exit(0)
